<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @checkAll="checkAll" @addEnter="addEnterFn"></TodoHeader>
    <TodoMain :list="showList" @del="delFn" @change="changeFn"></TodoMain>
    <TodoFooter :list="list" @clear="clearFn" @clickType="clickTypeFn" :type="type"></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
    
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";


export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todolist')) || [],
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      type:"all" //all表示显示全部 yes表示显示已完成 no表示显示未完成
    };
  },
  methods:{
    delFn(id) {
      // console.log('触发了',id)
      // filter筛选满足条件的 当前遍历的id不等于点击的id时满足条件
      this.list = this.list.filter(item=>item.id!==id)
    },
    changeFn(id) {
      // console.log('触发了changeFn',id)
      const res = this.list.find(item=>item.id===id)
      res.isDone = !res.isDone
    },
    checkAll(val) {
      // console.log('触发lecheckAll',val);
      this.list.forEach(item=>item.isDone=val)
    },
    addEnterFn(enter) {
      // console.log(enter)
      this.list.push({
        // 如果有长度就在最后一个id后面继续加 没有id就是100
        id:this.list.length ? this.list.at(-1).id+1 : 100,
        name:enter,
        isDone:false
      })
    },
    clearFn() {
      console.log('触发clearFn')
      this.list=this.list.filter(item=>item.isDone === false)
    },
    clickTypeFn(type) {
      this.type = type
    }

  },
  computed: {
    showList() {
      if(this.type === "yes") {
        return this.list.filter(item=>item.isDone)
      }else if(this.type === "no") {
        return this.list.filter(item=>!item.isDone)
      }else {
        return this.list
      }
    }
  },
  watch: {
    list: {
      deep:true,
      handler(newVal) {
        localStorage.setItem('todolist',JSON.stringify(newVal))
      }
    } 
  }

};
</script>